package org.javaboy.fmall.utils.returnTool;

import io.swagger.models.auth.In;
import org.javaboy.fmall.utils.generateTool.DataForTypeEnum;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

/**
 * @ClassName CustomException 异常捕获类
 * @Description
 * @Author find me
 * @Date 2020/7/19 0019 14:56
 * @Version 1.0
 */
@RestControllerAdvice
public class CustomException {

    /**
     * 如果返回的是定义的方法，就走定义的
     * @param e
     * @return
     */
    @ExceptionHandler({Exception.class})//拦截指定异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//指定游览器返回状态码
    public ResTool uniteExceptionHandler(Exception e) {
        e.printStackTrace();
        ColeMessage rest = this.getRest(HttpStatus.INTERNAL_SERVER_ERROR.value());
        if (rest != null) {
            return new ResTool().success(false).code(rest.getCode())
                    .msg(rest.getMessage()).error(e.getLocalizedMessage());
        }
        return new ResTool().success(false).code(HttpStatus.INTERNAL_SERVER_ERROR.value())
                .msg(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).error(e.getCause().toString());
    }


    @ExceptionHandler(BusinessException.class)
    public ResTool businessExceptionHandler(BusinessException e) {
        return new ResTool().success(false).code(e.getCode()).msg(e.getMsg());
    }


    @ExceptionHandler(SQLException.class)
    public ResTool SQLException(SQLException e) {
        e.printStackTrace();
        return new ResTool().success(false).code(e.getErrorCode()).msg(e.toString());
    }
    /**
     * 翻译系统返回的状态码是否符合自定义的状态码
     *
     * @param status
     * @return
     */
    private ColeMessage getRest(Integer status) {
        ColeMessage[] values = ColeMessage.values();
        for (ColeMessage value : values) {
            if (value.getCode() == status) {
                return value;

            }
        }
        return null;

    }
}